package com.sharkburner.aeris.faces.common.validation;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 * Password & Confirm Password validator. Example:
 * 
 * <pre>
 * &lt;h:inputSecret id="passwordInput" binding="#{passwordComponent}" required="true" /&gt;
 * <br/>
 * &lt;h:inputSecret id="confirmPassword" required="#{not empty passwordInput.value}"&gt;
 * 	&ltf:validator validatorId="confirmPasswordValidator" /&gt;
 * 	&ltf:attribute name="passwordComponent" value="#{passwordComponent}" /&gt;
 * &lt/h:inputSecret&gt;
 * </pre>
 * 
 * Pay attention to <b>binding</b>
 */
@FacesValidator(value = "confirmPasswordValidator")
public class ConfirmPasswordValidator implements Validator {
	private static final String PASSWORD_COMPONENT = "passwordComponent";
	private static final String MESSAGE_ID = "Confirm password";

	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {

		UIInput passwordComponent = (UIInput) component.getAttributes().get(
				PASSWORD_COMPONENT);
		String password = (String) passwordComponent.getValue();
		String confirmPassword = (String) value;
		if (password != null && !password.equals(confirmPassword)) {
			throw new ValidatorException(new FacesMessage(MESSAGE_ID));
		}
	}
}
